package com.pangu.service.impl;

import java.util.Date;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.ioc.aop.Aop;
import org.nutz.service.NameEntityService;

import com.pangu.domain.user.Account;
import com.pangu.domain.user.BasicInfo;
import com.pangu.security.AccountHelper;
import com.pangu.service.AccountService;

public class AccountServiceImpl extends NameEntityService<Object> implements AccountService {

	@Aop("transactionInterceptor")
	public Account addAccount(Account account) {
		String encodedPwd = AccountHelper.encryptPassword(account.getPassword());
		
		account.setActived(false);
		account.setActivekey(AccountHelper.generateActiveKey(account.getUsername()));
		account.setPassword(encodedPwd);
		account.setPwdanswer(encodedPwd);
		account.setPwdassist(account.getUsername());
		account.setRegtime(new Date());
		account.setType(Account.TYPE_UNACTIVE);
		dao().insert(account);
		
		BasicInfo basicInfo = new BasicInfo();
		basicInfo.setId(account.getId());
		basicInfo.setNickname(account.getUsername());
		dao().insert(basicInfo);
		
		return account;
	}

	public Account getAccountById(long uid) {
		return this.dao().fetch(Account.class, uid);
	}

	public Account getAccountByName(String username) {
		return this.dao().fetch(Account.class, username);
	}

	public Account getAccountByEmail(String email) {
		Condition cnd = Cnd.where("email", "=", email);
		List<Account> list = this.dao().query(Account.class, cnd, null);
		if (list != null && list.size() > 0)
			return list.get(0);
		return null;
	}

	public boolean existUsername(String username) {
		Account account = getAccountByName(username);
		return account != null;
	}

	public boolean existEmail(String email) {
		Account account = getAccountByEmail(email);
		return account != null;
	}

	public boolean existUsernameOrEmail(String username, String email) {
		Condition cnd = Cnd.where("username", "=", username).or("email", "=", email);
		List<Account> list = this.dao().query(Account.class, cnd, null);
		if (list != null && list.size() > 0)
			return true;
		return false;
	}

	public boolean modifyPassword(long uid, String password) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean modifyEmail(long uid, String email) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean modifyPwdAssist(long uid, String question, String answer) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean modifyLastLogInfo(long uid, String ip, Date date) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean active(long uid, String activeKey) {
		// TODO Auto-generated method stub
		return false;
	}

}
